//
//  HNQAViewController.m
//  JHFBaseProject
//
//  Created by 朱传正 on 2016/12/29.
//  Copyright © 2016年 好牛. All rights reserved.
//

#import "HNQAViewController.h"
#import "HNQATableCellOne.h"
#import "HNQATableViewCellTwo.h"
#import "HNQADetailController.h"
#import "HNSubmitProblemController.h"

@interface HNQAViewController ()


@property (nonatomic,strong)NSDictionary *problemListDic;
@property (nonatomic,strong)NSMutableArray *dataSource;
@property (nonatomic,assign) NSInteger currentCur;

@end

@implementation HNQAViewController

-(NSMutableArray *)dataSource{
    if (!_dataSource) {
        _dataSource = [[NSMutableArray alloc]init];
    }
    return _dataSource;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"问答";
    self.navigationController.navigationBar.titleTextAttributes = @{UITextAttributeTextColor: RGBJ(66),
                                                                    UITextAttributeFont : [UIFont boldSystemFontOfSize:14]};
    
    
    UIBarButtonItem * itemRight = [[UIBarButtonItem alloc]init];
    [itemRight setTitle:@"提问"];
    [itemRight setTarget:self];
    [itemRight setAction:@selector(consultClick:)];
    self.navigationItem.rightBarButtonItem=itemRight;
    
    
    MJRefreshGifHeader *header = [[MJRefreshGifHeader alloc]init];
        [header setRefreshingBlock:^(void){
            _currentCur = 1;
            [self getProboemListOrigin];
        }];
    self.tableView.mj_header = header;
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^(void){
        _currentCur ++;
        [self getProboemListData:_currentCur];
    }];
    
    
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    
    [self initData];
}



-(void)consultClick:(UIButton *)btn{
    HNSubmitProblemController *getMegVc = [[HNSubmitProblemController alloc]init];
    
    
    [self.navigationController pushViewController:getMegVc animated:YES];
}



-(void)initData{
    [self getProboemListOrigin];
}

#pragma -mark TableView
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _dataSource.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *problemDetailDic = [_dataSource objectAtIndex:indexPath.row];
    NSString *imageStr = [NSString stringWithFormat:@"%@",[problemDetailDic objectForKey:@"image"]];
    NSArray *imageStrArr = [imageStr componentsSeparatedByString:@","];
    
    if (imageStrArr.count < 3) {
        return 120;
    }else{
        //        return 171;
        static NSString *CellIdentifier = @"HNQATableViewCellTwo";
        HNQATableViewCellTwo *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[[NSBundle mainBundle] loadNibNamed:CellIdentifier owner:self options:nil]firstObject];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
        return cell.frame.size.height;
    }
    
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSDictionary *problemDetailDic = [_dataSource objectAtIndex:indexPath.row];
    NSString *imageStr = [NSString stringWithFormat:@"%@",[problemDetailDic objectForKey:@"image"]];
    NSArray *imageStrArr = [imageStr componentsSeparatedByString:@","];
    NSLog(@"%@",imageStrArr);
    
    if (imageStrArr.count < 3) {
        static NSString *CellIdentifier = @"HNQATableCellOne";
        HNQATableCellOne *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[[NSBundle mainBundle] loadNibNamed:CellIdentifier owner:self options:nil]firstObject];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
        cell.cellTitle.text = [NSString stringWithFormat:@"%@",[problemDetailDic objectForKey:@"briefContent"]];
        cell.cellDetail.text = [NSString stringWithFormat:@"%@",[problemDetailDic objectForKey:@"content"]];
        [cell.cellImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",url_Base,imageStrArr[0]]] placeholderImage:[UIImage imageNamed:@"detailImage.png"]] ;
        [cell.cellPersonImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",url_Base,[problemDetailDic objectForKey:@"photo"]]]placeholderImage:[UIImage imageNamed:@"detailImage.png"]] ;
        NSString *nickname = [NSString stringWithFormat:@"%@",[problemDetailDic objectForKey:@"nickname"]];
        NSString *mobile = [NSString stringWithFormat:@"%@",[problemDetailDic objectForKey:@"mobile"]];
        if ([AppConfig isStrNull:nickname]) {
                cell.cellPersonName.text = mobile;
        }else{
                cell.cellPersonName.text = nickname;
        }
    
        cell.cellPersonTime.text = [NSString stringWithFormat:@"%@",[problemDetailDic objectForKey:@"createTime"]];
        return cell;
    }else{
        static NSString *CellIdentifier = @"HNQATableViewCellTwo";
        HNQATableViewCellTwo *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[[NSBundle mainBundle] loadNibNamed:CellIdentifier owner:self options:nil]firstObject];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
        cell.cellTitle.text = [NSString stringWithFormat:@"%@",[problemDetailDic objectForKey:@"briefContent"]];
        cell.cellDetail.text = [NSString stringWithFormat:@"%@",[problemDetailDic objectForKey:@"content"]];
        
        
        [cell.cellPersonImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",url_Base,[problemDetailDic objectForKey:@"photo"]]]placeholderImage:[UIImage imageNamed:@"detailImage.png"]] ;
        [cell.imageView1 sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",url_Base,imageStrArr[0]]]placeholderImage:[UIImage imageNamed:@"detailImage.png"]] ;
        [cell.imageView2 sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",url_Base,imageStrArr[1]]]placeholderImage:[UIImage imageNamed:@"detailImage.png"]] ;
        
        [cell.imageView3 sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",url_Base,imageStrArr[2]]]placeholderImage:[UIImage imageNamed:@"detailImage.png"]] ;
        
        [cell.cellPersonImage sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",url_Base,[problemDetailDic objectForKey:@"photo"]]]placeholderImage:[UIImage imageNamed:@"detailImage.png"]] ;
        NSString *nickname = [NSString stringWithFormat:@"%@",[problemDetailDic objectForKey:@"nickname"]];
        NSString *mobile = [NSString stringWithFormat:@"%@",[problemDetailDic objectForKey:@"mobile"]];
        if ([AppConfig isStrNull:nickname]) {
            cell.cellPersonName.text = mobile;
        }else{
            cell.cellPersonName.text = nickname;
        }
        cell.cellPersonTime.text = [NSString stringWithFormat:@"%@",[problemDetailDic objectForKey:@"createTime"]];
        return cell;
    }
    
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    HNQADetailController *getMegVc = [[HNQADetailController alloc]init];
    NSDictionary *problemDetailDic = [_dataSource objectAtIndex:indexPath.row];
    NSString *postId = [NSString stringWithFormat:@"%@",[problemDetailDic objectForKey:@"postId"]];
    getMegVc.postId = postId;
    
    [self.navigationController pushViewController:getMegVc animated:YES];
    
    
}


#pragma mark - 初始化问题列表消息
-(void)getProboemListOrigin{
    _currentCur = 1;
    NSMutableDictionary *param = [NSMutableDictionary dictionaryWithObjectsAndKeys:static_sessionId,@"sessionId",nil];
    [param setObject:@"1" forKey:@"cur"];
    NSLog(@"param = %@",param);
    
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager manager] initWithBaseURL:[NSURL URLWithString:url_Base]];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:url_problem_list parameters:param progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSError * error;
        NSDictionary * data=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:&error];
        [self hideHud];
        if (error) {
            NSLog(@"====error1:%@",error);
            [self showHint:@"获取问题列表失败"];
            NSLog(@"==dict:%@",data);
            return;
        }
        NSLog(@"==dict:%@",data);
        
        NSString * result = [NSString stringWithFormat:@"%@",[data objectForKey:@"result"]];
        if ([result isEqualToString:@"1"]) {
            _problemListDic = [data objectForKey:@"obj"];
            NSLog(@"------obj = %@",_problemListDic);
            
            NSArray *problemListArr = [NSArray arrayWithArray:[_problemListDic objectForKey:@"result"]];
            [self.dataSource removeAllObjects];
            for (int i = 0; i < problemListArr.count; i ++) {
                [self.dataSource addObject:problemListArr[i]];
            }
            
            NSLog(@"===self.dataSource = %@",self.dataSource);
            
              [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer endRefreshing];
            
            [self.tableView reloadData];
            
            //
            //            [self.view bringSubviewToFront:self.selectSectionView];
            //
            //            _contentHeight = 0;
            //
            //            [self setDoctorList];
            //
            
            
            
        }else{
            NSString * info = [NSString stringWithFormat:@"%@",[data objectForKey:@"msg"]];
            if ([info isEqualToString:msg_InvalidLoginInformation]) {
                
                [AppConfig removeUserInfo];
                
                [[EMClient sharedClient] logout:YES];
                [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@NO];
                
                HNLoginViewController *loginVC = [[HNLoginViewController alloc]init];
                
                [self.navigationController pushViewController:loginVC animated:YES];
            }
            [self showHint:info];
             [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer endRefreshing];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull  error) {
        NSLog(@"====error:%@",error);
        [self hideHud];
        [self showHint:@"获取问题列表失败"];
         [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    }];
    
    
}


#pragma mark - 初始化问题列表消息
-(void)getProboemListData:(NSInteger)cur{
    
    NSMutableDictionary *param = [NSMutableDictionary dictionaryWithObjectsAndKeys:static_sessionId,@"sessionId",nil];
    [param setObject:[NSString stringWithFormat:@"%ld",cur] forKey:@"cur"];
    NSLog(@"param = %@",param);
    
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager manager] initWithBaseURL:[NSURL URLWithString:url_Base]];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:url_problem_list parameters:param progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSError * error;
        NSDictionary * data=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:&error];
        [self hideHud];
        if (error) {
            NSLog(@"====error1:%@",error);
            [self showHint:@"获取问题列表失败"];
            NSLog(@"==dict:%@",data);
            return;
        }
        NSLog(@"==dict:%@",data);
        
        NSString * result = [NSString stringWithFormat:@"%@",[data objectForKey:@"result"]];
        if ([result isEqualToString:@"1"]) {
            _problemListDic = [data objectForKey:@"obj"];
            NSLog(@"------obj = %@",_problemListDic);
            
            NSArray *problemListArr = [NSArray arrayWithArray:[_problemListDic objectForKey:@"result"]];
            if (problemListArr.count != 0) {
                for (int i = 0; i < problemListArr.count; i ++) {
                    [self.dataSource addObject:problemListArr[i]];
                }
            }
           
            
            NSLog(@"===self.dataSource = %@",self.dataSource);
            
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer endRefreshing];
            
            [self.tableView reloadData];
            
            //
            //            [self.view bringSubviewToFront:self.selectSectionView];
            //
            //            _contentHeight = 0;
            //
            //            [self setDoctorList];
            //
            
            
            
        }else{
            NSString * info = [NSString stringWithFormat:@"%@",[data objectForKey:@"msg"]];
            if ([info isEqualToString:msg_InvalidLoginInformation]) {
                
                [AppConfig removeUserInfo];
                
                [[EMClient sharedClient] logout:YES];
                [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@NO];
                
                HNLoginViewController *loginVC = [[HNLoginViewController alloc]init];
                
                [self.navigationController pushViewController:loginVC animated:YES];
            }
            [self showHint:info];
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer endRefreshing];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull  error) {
        NSLog(@"====error:%@",error);
        [self hideHud];
        [self showHint:@"获取问题列表失败"];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    }];
    
    
}




@end
